package org.example.controller;

import com.alibaba.fastjson.JSONArray;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import org.example.bean.Alipay;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/alipay")
public class AlipayController {
    @Value("${appId}")
    private String appId;
    @Value("${privateKey}")
    private String privateKey;
    @Value("${publicKey}")
    private String publicKey;
    @Value("${notifyUrl}")
    private String notifyUrl;
    @Value("${returnUrl}")
    private String returnUrl;
    @Value("${signType}")
    private String signType;
    @Value("${charset}")
    private String charset;
    @Value("${gatewayUrl}")
    private String gatewayUrl;
    @RequestMapping("/pay")
    public String pay(Alipay alipayBean) throws AlipayApiException {
// 产⽣Alipay客户端
        AlipayClient alipayClient = new DefaultAlipayClient(gatewayUrl, appId, privateKey,
                "json", charset, publicKey, signType);
// 调⽤⽀付宝接⼝
        AlipayTradePagePayRequest alipayTradeAppPayRequest = new
                AlipayTradePagePayRequest();
        System.out.println("进⼊了这⾥：" + alipayBean);
// 设置付款成功后应跳转的路径
        alipayTradeAppPayRequest.setNotifyUrl(notifyUrl);
        alipayTradeAppPayRequest.setReturnUrl(returnUrl);
// 设置⽀付宝的各项参数
        String json = JSONArray.toJSONString(alipayBean);
        alipayTradeAppPayRequest.setBizContent(json);
        System.out.println("⽀付的参数是：" + json);
        System.out.println(JSONArray.toJSONString(alipayTradeAppPayRequest));
// ⽣成最终的订单
        return alipayClient.pageExecute(alipayTradeAppPayRequest).getBody();
    }
    @GetMapping("/success")
    public String success(){
        return "⽀付成功";
    }
}
